﻿using Deployment.Data.Environment.Connection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Deployment.Data.UI.Dialogs.Connection
{
    /// <summary>
    /// Interaction logic for EditConnectionDialog.xaml
    /// </summary>
    public partial class EditConnectionDialog : Window
    {
        private Data.Environment.Environment _environment;
        private bool _AllowClose = true;
        private bool _Testing = false;
        

        public EditConnectionDialog()
        {
            InitializeComponent();
        }

        public EditConnectionDialog(Data.Environment.Environment environment)
        {
            InitializeComponent();
            this._environment = environment;
        }

        public EditConnectionDialog(Data.Environment.Environment environment, AbstractConnection connection)
        {
            InitializeComponent();
            this._environment = environment;
            if (connection != null)
            {
                Control.IsEditMode = true;
                this.Title = string.Format("Edit Connection '{0}'", connection.Name);
                Control.DataContext = connection;
            }
        }

        public AbstractConnection Connection { get { return Control.DataContext as AbstractConnection; } }

        internal Data.Environment.Environment Environment
        {
            get { return this._environment; }
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            if (_environment != null)
            {
                foreach (AbstractConnection con in _environment.Connections)
                {
                    if (string.Equals(con.Name, (this.Control.DataContext as AbstractConnection).Name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (!this.Control.DataContext.GetType().Equals(con.GetType()))
                        {
                            _AllowClose = false;
                            DialogResult = false;
                            MessageBox.Show(this, "Connections with the same name must also be the same type.", "Type Mismatch",
                                MessageBoxButton.OK, MessageBoxImage.Hand);
                            return;
                        }
                    }
                }
                DialogResult = true;
            }
            else
            {
                DialogResult = true;
            }
            Close();
        }

        private void Test_Click(object sender, RoutedEventArgs e)
        {
            if (!(Control.DataContext as AbstractConnection).IsConnectionTesting)
            {
                this.Cursor = Cursors.Wait;
                BackgroundWorker worker = new BackgroundWorker();
                worker.RunWorkerCompleted += worker_RunWorkerCompleted;
                worker.DoWork += worker_DoWork;
                this.btn_TestConnection.IsEnabled = false;
                worker.RunWorkerAsync(Control.DataContext as AbstractConnection);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_AllowClose)
                e.Cancel = true;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            AbstractConnection connection = e.Argument as AbstractConnection;
            if (connection != null)
            {
                connection.ValidateConnection();
                while (connection.IsConnectionTesting)
                {
                    Thread.Sleep(300);
                }
                e.Result = null;
            }
            else
            {
                e.Result = "Unable to test null Connection.";
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Cursor = Cursors.Arrow;

            if (e.Result as string != null)
            {
                MessageBox.Show(e.Result as string, "Test Error");
                return;
            }

            AbstractConnection connection = Control.DataContext as AbstractConnection;
            this.btn_TestConnection.IsEnabled = connection.IsConnectionDataValid;
            if (connection != null)
            {
                if (connection.ConnectionTestedSuccessfully && string.IsNullOrEmpty(connection.FailureMessage))
                {
                    MessageBox.Show(this, "Connection tested successfully.", "Connection Test", MessageBoxButton.OK, MessageBoxImage.None);
                }
                else
                {
                    if (connection.ConnectionTestedSuccessfully)
                    {
                        MessageBox.Show(this, connection.FailureMessage, "Connection Test", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        MessageBox.Show(this, connection.FailureMessage, "Connection Test Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }

                }
            }
        }
        

        
    }
}
